import memoizeOne from 'memoize-one'
import isEqual from 'lodash/isEqual'

export const check = authorities => (...args) => {
    authorities = authorities || []
    if (args.length === 0) return true;
    if (args.length > 1) {
        // 任意一项返回true即返回true，否则返回false
        return args.some(_ => check(authorities)(_))
    } else {
        const auths = args[0]
        if (auths === undefined) {
            return true
        } else if (typeof auths === 'string') {
            return authorities.indexOf(auths) !== -1
        } else if (Array.isArray(auths)) {
            // 每一项都返回true才返回true，否则返回false
            return auths.every(_ => check(authorities)(_))
        }
    }
}

export const checkRouteAuth = authorities => auth => {
    if (auth) {
        let auths
        if (typeof auth === 'string' && (auths = auth.split('|').map(_ => _.trim())).length > 1) {
            return check(authorities)(...auths)
        }
        return check(authorities)(auth)
    } else {
        return true
    }
}

const formatter = (data, authorities) => {
    return (data || []).map(item => {
        const _item = {
            ...item
        }
        if (item.children) {
            _item.children = formatter(item.children, authorities)
        }
        return _item
    })
    .filter(item => item && item.name && item.path)
    .filter(item => checkRouteAuth(authorities)(item.authority))
}
export const formatterData = memoizeOne(formatter, isEqual)